package com.iflytek.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iflytek.entity.User;
import com.iflytek.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String toLogin() {
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(String username, String password,
                          HttpSession session) {

        //TODO 和数据库中的用户名密码比对
        QueryWrapper<User> w = new QueryWrapper<User>();
        w.eq("name", username);
        w.and(
                weapper -> weapper.eq("password", password)
        );
        if (userService.getOne(w) != null) {
            //登录成功
            System.out.println("登录成功！！！！");
            //把用户的信息放入Session
            session.setAttribute("username", username);
            return "login";
        } else {
            System.out.println("登录失败！！！！");
            return "login";
        }

    }

    @ResponseBody
    @GetMapping("/findUsername")
    public String findUsername(String username) {
        QueryWrapper<User> w = new QueryWrapper<User>().eq("name", username);
        User user = userService.getOne(w);
        if (user != null) {
            return "用户名正确";
        } else return "用户名不正确";

    }
}
